#include "../source/server.hpp"

using namespace wyl;

//普通套接字读取的处理函数

void HandleClose(Channel* channel)
{
    std::cout << " close : " << channel->GetFd() << std::endl;
    channel->Del();
    close(channel->GetFd());
    delete channel;
}

void HandleRead(Channel* channel)
{
    int fd = channel->GetFd(); //获取处理事件的文件描述符
    char buff[1024] = {0} ;
    int n = recv(fd,buff,sizeof(buff) - 1, 0); 
    if(n <= 0 )
    {
        HandleClose(channel);
        DLOG("read failed");
        return ;
    }
    std::cout << buff << std::endl;
    channel->EnableWrite(true); //启动写事件
}

void HandleWrite(Channel* channel)
{
    int fd = channel->GetFd();
    const char* mes = "你好呀！"; 
    int n = send(fd,mes,strlen(mes),0);
    if(n <= 0)
    {
        HandleClose(channel);
        DLOG("send failed");
        return;
    }
    DLOG("给客户端%d发送了一条数据：你好呀！",channel->GetFd());
    channel->EnableWrite(false); //关闭写事件
    if(!channel->WriteAble()) DLOG("写事件关闭成功");
}

void HandleError(Channel* channel)
{
    HandleClose(channel);
}

void HandleEvent(EventLoop* loop,Channel* channel,int timerid)
{
   loop->TimerRefresh(timerid);
}

std::unordered_map<uint64_t,PtrConnection> conns;
uint64_t conn_id = 0;

void ConnectionDestroy(const PtrConnection& conn)
{
    conns.erase(conn->Id()); 
}


EventLoop base_loop;
ThreadLoopPool* loop_pool;



int main(){

    
    Acceptor ac(&base_loop,8082);
    ac.SetAcceprCallBack(std::bind(NewConnection,std::placeholders::_1));
    ac.Listen();
    while(1)
    {
        base_loop.Start();
        // std::vector<Channel*> actives; 
        // actives.WaitEpoll(&actives); //持续监听 poller，并把连接对象放进actives中
        // for(auto& e : actives)
        // {
        //     e->HandleEvent(); //调用连接的事件处理
        // }
    }
    //int new_fd = sock.Accept();
    // if(new_fd < 0)
    // {
    //     std::cout << "Accept failed" << std::endl;
    //     return -1;
    // }

    // Socket client(new_fd); 
    // char buff[1024] = {0};
    // client.Recv(buff,1023);
    // DLOG("%s", buff);

    return 0 ; 
}
